# 如果要让烟花在窗口上半部分炸开，我们可以修改 launch 方法，使烟花在达到一定高度后就炸开，并且在窗口上半部分位置炸开。
# 下面是一个修改后的示例代码，其中烟花在窗口上半部分位置炸开。

import pygame
import random
import numpy as np

# 初始化 Pygame
pygame.init()

# 设置窗口尺寸
screen = pygame.display.set_mode((800, 600))

# 定义音效生成函数
def generate_explosion_sound(frequency, duration, volume):
    sample_rate = 44100
    t = np.linspace(0, duration, int(sample_rate * duration), False)
    audio_data = (volume * np.sin(2 * np.pi * frequency * t)).astype(np.int16)
    return pygame.sndarray.make_sound(np.column_stack((audio_data, audio_data)))

# 定义烟花类
class Firework:
    def __init__(self):
        self.x = random.randint(200, 600)
        self.y = 600
        self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        self.radius = 3
        self.speed = random.randint(1, 5)
        self.explosion_sounds = [
            generate_explosion_sound(440, 1.0, 0.5),
            generate_explosion_sound(550, 1.2, 0.6),
            generate_explosion_sound(660, 1.4, 0.7)
        ]

    def launch(self):
        if self.y > 300:
            random.choice(self.explosion_sounds).play()
            self.radius += 1
            if self.radius > 30:
                self.reset()
        else:
            self.y -= self.speed

    def reset(self):
        self.x = random.randint(200, 600)
        self.y = 600
        self.radius = 3
        self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        self.speed = random.randint(1, 5)

    def draw(self):
        pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius)

# 创建烟花实例
firework = Firework()

# 游戏循环
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((0, 0, 0))
    firework.launch()
    firework.draw()
    pygame.display.flip()

pygame.quit()